<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <span>省市区级联选择器测试</span>
      </template>
      
      <el-form :model="form" label-width="120px">
        <el-form-item label="所在地区">
          <el-cascader
            v-model="form.regionIds"
            :options="regionOptions"
            :props="cascaderProps"
            placeholder="请选择省市区"
            style="width: 100%"
            clearable
            @change="handleRegionChange"
          />
        </el-form-item>
        
        <el-form-item label="省份名称">
          <el-input v-model="form.province" readonly />
        </el-form-item>
        
        <el-form-item label="城市名称">
          <el-input v-model="form.city" readonly />
        </el-form-item>
        
        <el-form-item label="区县名称">
          <el-input v-model="form.district" readonly />
        </el-form-item>
        
        <el-form-item label="详细地址">
          <el-input 
            v-model="form.address" 
            placeholder="请输入详细地址" 
            type="textarea" 
            :rows="3"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">提交</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
      
      <el-divider />
      
      <div>
        <h4>选择结果：</h4>
        <pre>{{ JSON.stringify(form, null, 2) }}</pre>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { transformData, getRegionNames, getRegionIds } from "@/utils/region"

// 省市区级联选择器配置
const regionOptions = ref(transformData())
const cascaderProps = {
  value: 'value',
  label: 'label',
  children: 'children',
  checkStrictly: false,
  emitPath: true
}

const form = reactive({
  regionIds: [],
  province: '',
  city: '',
  district: '',
  address: ''
})

// 省市区选择器变化处理
function handleRegionChange(value) {
  if (value && value.length >= 3) {
    const [provinceId, cityId, districtId] = value
    const regionNames = getRegionNames(provinceId, cityId, districtId)
    
    // 更新表单中的省市区名称字段
    form.province = regionNames.province
    form.city = regionNames.city
    form.district = regionNames.district
  } else {
    // 清空省市区名称
    form.province = ''
    form.city = ''
    form.district = ''
  }
}

function handleSubmit() {
  console.log('提交的表单数据：', form)
  ElMessage.success('提交成功！')
}

function handleReset() {
  form.regionIds = []
  form.province = ''
  form.city = ''
  form.district = ''
  form.address = ''
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

pre {
  background-color: #f5f5f5;
  padding: 15px;
  border-radius: 4px;
  font-size: 12px;
  overflow-x: auto;
}
</style> 